class Document < ActiveRecord::Base

    def self.save(upload)

        name = Document.sanitize_filename(upload['title'])
        filetype = upload['datafile'].original_filename
        filetype = filetype.split(".")
        filetype = filetype[filetype.length-1]
        if upload['date'][5] == " " and upload['date'][8] == " "
          upload['date'][5] = "-"
          upload['date'][8] = "-"
        end
        tags = upload['doc_type'] + upload['date']
        name =  tags + name + "." + filetype
        directory = "#{RAILS_ROOT}/Documents"
        # create the file path
        path = File.join(directory, name)
        # write the file
        File.open(path, "wb") { |f| f.write(upload['datafile'].read) }

    end

    def self.delete(document)

        directory = "#{RAILS_ROOT}/Documents"
        path = File.join(directory, document)
        File.delete(path)

    end

    def self.sanitize_filename(file_name)

        # get only the filename, not the whole path (from IE)
        just_filename = file_name#File.basename(file_name)
        # replace all none alphanumeric, underscore or perioids
        # with underscore
        just_filename.sub(/[\t\.\-]/,'_')

    end
    
    def self.get_documents
      documents = Dir.chdir("#{RAILS_ROOT}/Documents/") do Dir.glob("*") end
  
      documents.sort! { |a,b| Time.parse(a[1, 10]) <=> Time.parse(b[1, 10]) }
      documents.reverse
    end
    
    def self.get_src
      documents = Dir.chdir("#{RAILS_ROOT}/Documents/") do Dir.glob("5*") end
  
      documents.sort! { |a,b| Time.parse(a[1, 10]) <=> Time.parse(b[1, 10]) }
      documents.reverse[0]
    end

end
